<template>
  <div>
    <div v-if="flag == 0">
      <div class="mlt">
        <el-button
          v-permissions="{ permission: ['add:Staff'] }"
          type="primary"
          @click="addRole"
        >
          添加员工
        </el-button>
      </div>
      <!-- table 表格 -->
      <div class="ml">
        <el-table
          border
          :data="tableData2"
          :span-method="objectSpanMethod"
          style="width: 100%; margin-top: 20px"
        >
          <!-- <el-table-column label="ID" prop="ids" width="180" /> -->
          <el-table-column label="姓名" prop="real_name" />
          <el-table-column label="角色" prop="role_name" />
          <el-table-column :label="langs.page.dept + '/' + '职位'">
            <template slot-scope="scope">
              <div v-if="!scope.row.dept_name">
                <el-tag>请选择部门</el-tag>
              </div>
              <div v-else>
                {{ scope.row.dept_name }}/ {{ scope.row.group_name }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template v-if="scope.row.group_name" slot-scope="scope">
              <el-button
                v-permissions="{ permission: ['set-dept:Staff'] }"
                size="mini"
                type="text"
                @click="editEmployee(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.is_res == 'Y'"
                v-permissions="{ permission: ['set-recive:Staff'] }"
                size="mini"
                type="text"
                @click="receptionModule(scope.row)"
              >
                {{ langs.page.template_name }}
              </el-button>
              <el-button
                v-if="scope.row.is_res == 'Y'"
                v-permissions="{ permission: ['set-template:Staff'] }"
                size="mini"
                type="text"
                @click="record(scope.row)"
              >
                模板管理
              </el-button>
              <el-button
                v-permissions="{ permission: ['set-dept:Staff'] }"
                size="mini"
                type="text"
                @click="deleteEmployee(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="客服">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.service_status"
                v-permissions="{ permission: ['set-service:Staff'] }"
                active-color="#13ce66"
                active-value="Y"
                inactive-color="#ff4949"
                inactive-value="N"
                @change="addcustomerqx(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="设置">
            <template slot-scope="scope">
              <el-button
                v-permissions="{ permission: ['set-dept:Staff'] }"
                size="mini"
                type="text"
                @click="addOrganization(scope.row)"
              >
                设置部门职位
              </el-button>
              <el-button
                v-permissions="{ permission: ['edit:Staff'] }"
                size="mini"
                type="text"
                @click="editStaff(scope.row)"
              >
                编辑员工
              </el-button>
              <!-- <el-button
                v-permissions="{ permission: ['edit:Staff'] }"
                size="mini"
                type="text"
                @click="userSets(scope.row)"
              >
                设置离职
              </el-button> -->
            </template>
          </el-table-column>
          <el-table-column label="是否在职">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                v-permissions="{ permission: ['set-service:Staff'] }"
                active-color="#13ce66"
                active-value="on_job"
                inactive-color="#ff4949"
                inactive-value="quit_job"
                @change="userSets(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加 -->
      <el-dialog
        :before-close="handleClose"
        title="添加"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <el-form
          ref="ruleForm"
          class="demo-ruleForm"
          label-width="100px"
          :model="ruleForm"
        >
          <el-form-item :label="langs.page.dept" prop="">
            <el-select
              v-model="ruleForm.department"
              placeholder="请选择"
              @change="handleChange"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.dept_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职位" prop="">
            <el-select
              v-model="ruleForm.position"
              placeholder="请选择"
              @change="GroupChange"
            >
              <el-option
                v-for="item in GroupOptions"
                :key="item.id"
                :label="item.group_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- 可预约岗位选择商品 -->
          <el-form-item v-if="commodity">
            <el-button type="primary" @click="addTest">
              关联{{ langs.page.goods_select_tag }}
            </el-button>
          </el-form-item>
          <!-- 教培的不需要 预约金 -->
          <div v-if="commodity">
            <table class="tftable" style="width: 98%">
              <thead>
                <tr>
                  <td colspan="1" style="width: 200px">商品名称</td>
                  <td v-if="type != 'school'" colspan="1">预约金</td>
                  <td v-if="type != 'school'" colspan="1">总费用</td>
                  <td colspan="1" style="width: 100px">删除</td>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in items" :key="index">
                  <td>
                    <el-select
                      v-model="item.goods_id"
                      placeholder="请选择"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="itemes in GoodsOptions"
                        :key="itemes.goods_id"
                        :label="itemes.type_goods_name"
                        :value="itemes.goods_id"
                        @click.native="
                          GoodsChange(index, itemes.goods_attr_price)
                        "
                      />
                    </el-select>
                  </td>
                  <td v-if="type != 'school'">
                    <!-- <el-input
                      v-model.number="item.res_fee"
                      oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                      placeholder="请输入预约金 "
                      style="width: 130px"
                    /> -->
                    <el-input-number
                      v-model="item.res_fee"
                      :max="Number(item.total_fee)"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                    />
                  </td>
                  <td v-if="type != 'school'">
                    <el-input
                      v-model="item.total_fee"
                      :disabled="true"
                      placeholder="请输入总费用 "
                      style="width: 110px"
                    />
                  </td>
                  <td colspan="1" style="width: 100px">
                    <el-button type="danger" @click.prevent="deleteTest(index)">
                      删除
                    </el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="Submit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑 -->
      <el-dialog
        :before-close="handleClose"
        title="编辑部门"
        :visible.sync="dialogVisibles"
        width="50%"
      >
        <el-form
          ref="ruleForm"
          class="demo-ruleForm"
          label-width="100px"
          :model="ruleForm"
        >
          <el-form-item :label="langs.page.dept" prop="">
            <el-select
              v-model="ruleForm.department"
              placeholder="请选择"
              @change="editHandleChange"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.dept_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="职位" prop="">
            <el-select
              v-model="ruleForm.position"
              placeholder="请选择"
              @change="GroupChange"
            >
              <el-option
                v-for="item in GroupOptions"
                :key="item.id"
                :label="item.group_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- 可预约岗位选择商品 -->
          <el-form-item v-if="commodity">
            <el-button type="primary" @click="addTest">
              关联{{ langs.page.goods_select_tag }}
            </el-button>
          </el-form-item>
          <div v-if="commodity">
            <table class="tftable" style="width: 98%">
              <thead>
                <tr>
                  <td colspan="1" style="width: 200px">商品名称</td>
                  <td v-if="type != 'school'" colspan="1">预约金</td>
                  <td v-if="type != 'school'" colspan="1">总费用</td>
                  <td colspan="1" style="width: 100px">删除</td>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in items" :key="index">
                  <td>
                    <el-select
                      v-model="item.goods_id"
                      placeholder="请选择"
                      style="width: 200px"
                    >
                      <el-option
                        v-for="itemes in GoodsOptions"
                        :key="itemes.goods_id"
                        :label="itemes.type_goods_name"
                        :value="itemes.goods_id"
                        @click.native="
                          GoodsChange(index, itemes.goods_attr_price)
                        "
                      />
                    </el-select>
                  </td>
                  <td v-if="type != 'school'">
                    <!-- <el-input
                      v-model.number="item.res_fee"
                      oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                      placeholder="请输入预约金 "
                      style="width: 130px"
                    /> -->
                    <el-input-number
                      v-model="item.res_fee"
                      :max="Number(item.total_fee)"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                    />
                  </td>
                  <td v-if="type != 'school'">
                    <el-input
                      v-model="item.total_fee"
                      :disabled="true"
                      placeholder="请输入总费用 "
                      style="width: 110px"
                    />
                  </td>
                  <td colspan="1" style="width: 100px">
                    <el-button type="danger" @click.prevent="deleteTest(index)">
                      删除
                    </el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCancel">取 消</el-button>
          <el-button type="primary" @click="editSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- <div v-if="total != '' && total == true">
        <el-pagination background layout="prev, pager, next" :total="total" />
      </div> -->
      <el-pagination
        v-if="total >= 10"
        background
        :current-page.sync="page"
        layout="prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

    <div v-if="flag == 1">
      <AddEmployee :obj="obj" @showMain="showMain" />
    </div>
    <div v-if="flag == 2">
      <RecordTempletList :ids="ids" @showMain="showMain" />
    </div>
    <div v-if="flag == 3">
      <AddReceptionModule :ids="ids" @showMain="showMain" />
    </div>
  </div>
</template>

<script>
  import AddEmployee from './components/addEmployee.vue'
  import RecordTempletList from './components/recordTempletList.vue'
  import AddReceptionModule from './components/addReceptionModule.vue'
  import { getDeptLists } from '@/api/addOrganization'
  import { getGroup } from '@/api/group'
  import { getGoodsList } from '@/api/public'

  // import { delDepartment } from '@/api/addOrganization'
  import {
    getUserList,
    userDel,
    userDeptAdd,
    userDetail,
    setService,
    cancalService,
    userSet,
  } from '@/api/staff'
  export default {
    name: 'Reception',
    components: {
      AddEmployee,
      RecordTempletList,
      AddReceptionModule,
    },
    data() {
      return {
        items: [],
        pagesize: '10',
        page: 1,

        total: '',
        table: true,
        dialogVisible: false,
        dialogVisibles: false,
        //切换页面状态
        flag: 0,
        form: {},
        pid: 0,
        tableData2: [],
        departmentOptions: [],
        GroupOptions: [],
        GoodsOptions: [],
        ruleForm: {
          position: '',
        },
        commodity: false,
        user_id: '',
        state: {},
        userid: '',
        obj: {},
        editData: [],
        is_res: '',
        type: window.localStorage.getItem('mec_type'),
        langs: JSON.parse(window.localStorage.getItem('lang')),
      }
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {
      this.init()
    },
    methods: {
      // 初始化
      init() {
        this.getUser()
      },
      // 获取员工 列表
      getUser() {
        const loading = this.$loading({
          lock: true,
          target:
            this.tableData2.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        const params = {
          pagesize: this.pagesize,
          page: this.page,
        }
        getUserList(params).then((res) => {
          const tableData = res.data.data
          tableData.forEach((e) => {
            if (e.child.length == 0) {
              const ro = {
                ids: e.id,
                username: e.username,
                real_name: e.real_name,
                role_name: e.role_name,
                auth_tel: e.auth_tel,
                avatar: e.avatar,
                gender: e.gender,
                is_super: e.is_super,
                status: e.status,
                role_id: e.role_id,
              }
              e.child.push(ro)
            }
            e.child.forEach((a) => {
              a.ids = e.id
              a.username = e.username
              a.real_name = e.real_name
              a.role_name = e.role_name
              a.auth_tel = e.auth_tel
              a.avatar = e.avatar
              a.gender = e.gender
              a.is_super = e.is_super
              a.status = e.status
              a.service_status = e.service_status
              a.role_id = e.role_id
            })
            e.child[0].length = e.child.length
          })
          const arr = []
          tableData.forEach((e) => {
            e.child.forEach((e) => {
              arr.push(e)
            })
          })
          this.tableData2 = arr
          this.total = res.data.total
          loading.close()
        })
        getDeptLists().then((res) => {
          this.departmentOptions = res.data
        })
        if (window.localStorage.getItem('mec_type') == 'school') {
          const dada = {
            goods_type: 'curriculum',
          }
          getGoodsList(dada).then((res) => {
            this.GoodsOptions = res.data
          })
        } else {
          const dada = {
            goods_type: 'service',
          }
          getGoodsList(dada).then((res) => {
            this.GoodsOptions = res.data
          })
        }
      },

      // 编辑员工
      editEmployee(res) {
        this.items = []

        this.commodity = false
        const params = {
          id: res.id,
        }
        userDetail(params).then((e) => {
          console.log(e.data.dept_id)

          const params = {
            user_id: res.ids,
            dept_id: e.data.dept_id,
          }
          getGroup(params).then((res) => {
            res.data.forEach((j) => {
              if (e.is_partake == 'Y') {
                j.group_name = j.group_name + '(可预约)'
              }
            })
            this.GroupOptions = res.data
          })
          this.dialogVisibles = true
          this.editData = e.data
          this.ruleForm.department = e.data.dept_name
          this.ruleForm.position = e.data.group_name
          this.form.dept_id = e.data.dept_id
          this.form.group_id = e.data.group_id
          if (e.data.is_res == 'Y') {
            this.commodity = true
            this.items = e.data.child
            this.is_res = 'Y'
          } else {
            this.is_res = 'N'
          }
        })
        this.form.id = res.id
        this.obj = res
        this.user_id = res.ids
      },
      userSets(e) {
        const data = {
          id: e.ids,
          status: e.status,
        }
        userSet(data).then((r) => {
          console.log(r)
          this.init()
        })
      }, // 接诊模块
      receptionModule(e) {
        this.ids = e.ids
        this.flag = 3
      },
      // 儿保记录模板
      record(e) {
        this.ids = e.ids
        this.flag = 2
      },
      // 删除
      deleteEmployee(res) {
        const params = {
          id: res.id,
        }
        userDel(params).then(() => {})
        this.init()
      },
      // 添加部门
      addOrganization(e) {
        this.form = {}
        this.ruleForm = {
          position: '',
          department: '',
        }
        this.items = []
        this.user_id = e.ids
        this.commodity = false
        this.dialogVisible = true
        // this.form.id = e
        // this.addRole()
      },
      // 设置客服
      addcustomer(e) {
        console.log(e)
        const data = {
          user_id: e.ids,
        }
        setService(data)
          .then(() => {
            this.init()
            this.$message({
              message: '成功',
              type: 'success',
            })
          })
          .catch(() => {
            this.$message.error('失败')
          })
      },
      addcustomerqx(e) {
        const data = {
          user_id: e.ids,
        }
        if (e.service_status == 'Y') {
          setService(data)
            .then(() => {
              this.init()
              this.$message({
                message: '成功',
                type: 'success',
              })
            })
            .catch(() => {
              this.$message.error('失败')
            })
        } else {
          cancalService(data)
            .then(() => {
              this.init()
              this.$message({
                message: '成功',
                type: 'success',
              })
            })
            .catch(() => {
              this.$message.error('失败')
            })
        }
      },
      editStaff(e) {
        this.obj = {}
        this.obj = e
        this.flag = 1
        console.log(e)
      },
      showMain(e) {
        this.flag = e
        this.userid = ''
        this.$nextTick(() => {
          this.init()
        })
      },
      // 部门
      handleChange(e) {
        this.ruleForm.position = ''
        this.GroupOptions = []
        this.items = []
        this.commodity = false
        const params = {
          user_id: this.user_id,
          dept_id: e,
        }
        getGroup(params).then((res) => {
          res.data.forEach((e) => {
            if (e.is_partake == 'Y') {
              e.group_name = e.group_name + '(可预约)'
            }
          })
          //

          this.GroupOptions = res.data
          this.form.dept_id = e
        })
        this.form.dept_id = e
      },
      //编辑部门下拉框事件
      editHandleChange(e) {
        this.ruleForm.position = ''
        this.GroupOptions = []
        this.items = []
        this.commodity = false

        const params = {
          user_id: this.user_id,
          dept_id: e,
        }
        getGroup(params).then((res) => {
          res.data.forEach((e) => {
            if (e.is_partake == 'Y') {
              e.group_name = e.group_name + '(可预约)'
            }
          })

          this.GroupOptions = res.data
          this.form.dept_id = e
        })
      },
      // 职位
      GroupChange(e) {
        // const star = {}
        this.GroupOptions.forEach((res) => {
          if (res.id == e) {
            if (res.is_partake == 'Y') {
              this.commodity = true
              this.form.is_res = 'Y'
            } else {
              this.form.is_res = 'N'
              this.commodity = false
              this.items = []
            }
            this.state = res
          }
        })
        this.form.group_id = e
      },
      // 商品
      GoodsChange(e, r) {
        this.items[e].total_fee = r
        console.log(this.items[e])
        // this.form.goods_id = e
      },
      // 添加角色
      addRole() {
        this.obj = {}
        this.flag = 1
      },
      // 提交
      Submit() {
        this.form.user_id = this.user_id
        if (this.state.is_partake == 'Y') {
          const group_goods = JSON.stringify(this.items)
          this.form.group_goods = group_goods
          this.form.is_res = 'Y'
        } else {
          this.form.is_res = 'N'
          this.form.group_goods = ''
        }
        userDeptAdd(this.form)
          .then(() => {
            this.commodity = false
            this.form = {}
            this.items = []
            this.ruleForm = {
              position: '',
              department: '',
            }
            this.init()
            this.dialogVisible = false
            this.$message({
              message: '成功',
              type: 'success',
            })
          })
          .catch(() => {
            this.$message.error('失败')
          })
      },
      editSubmit() {
        this.form.user_id = this.user_id
        if (this.is_res == 'Y') {
          const group_goods = JSON.stringify(this.items)
          this.form.group_goods = group_goods
          this.form.is_res = 'Y'
        } else {
          this.form.is_res = 'N'
          this.form.group_goods = ''
        }

        userDeptAdd(this.form)
          .then(() => {
            this.commodity = false
            this.form = {}
            this.items = []
            this.ruleForm = {
              position: '',
              department: '',
            }
            this.init()
            this.dialogVisibles = false
            this.$message({
              message: '成功',
              type: 'success',
            })
          })
          .catch(() => {
            this.$message.error('失败')
          })
      },
      // 编辑弹框取消
      editCancel() {
        this.dialogVisibles = false
      },
      // 取消
      cancel() {
        this.commodity = false
        this.dialogVisible = false
        // this.items = {}

        this.form = {}
        this.ruleForm = {
          position: '',
          department: '',
        }
      },
      // 分页
      handleCurrentChange(val) {
        const _this = this
        _this.page = val
        this.init()
      },
      // 弹框回调
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
            this.commodity = false
            this.form = {}
            this.ruleForm = {
              position: '',
              department: '',
            }
          })
          .catch(() => {})
      },
      caseTypeNamesFormat(row) {
        let showProp = null
        row.dept_name ? (showProp = row.dept_name) : (showProp = '请选择部门')
        return showProp
      },
      Format(row) {
        let showProp = null
        row.group_name ? (showProp = row.group_name) : (showProp = '请选择岗位')
        return showProp
      },
      objectSpanMethod({ row, columnIndex }) {
        if (columnIndex === 0) {
          if (row.length) {
            return {
              rowspan: row.length,
              colspan: 1,
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        }
        if (columnIndex === 1) {
          if (row.length) {
            return {
              rowspan: row.length,
              colspan: 1,
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        }
        // if (columnIndex === 2) {
        //   if (row.length) {
        //     return {
        //       rowspan: row.length,
        //       colspan: 1,
        //     }
        //   } else {
        //     return {
        //       rowspan: 0,
        //       colspan: 0,
        //     }
        //   }
        // }
        if (columnIndex === 5) {
          if (row.length) {
            return {
              rowspan: row.length,
              colspan: 1,
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        }
        if (columnIndex === 6) {
          if (row.length) {
            return {
              rowspan: row.length,
              colspan: 1,
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0,
            }
          }
        }
      },
      addTest() {
        if (this.items.length < this.GoodsOptions.length) {
          this.items.push({
            goods_id: '',
            res_fee: '0',
            total_fee: '0',
          })
        } else {
          this.$message({
            type: 'success',
            message: '已选择全部商品!',
          })
        }
      },
      deleteTest(index) {
        this.items.splice(index, 1)
      },
    },
  }
</script>

<style scoped>
  table.tftable,
  table.table-count {
    font-size: 12px;
    color: #333333;
    width: 100%;
    border-width: 1px;
    border-collapse: collapse;
  }

  table.table-count th,
  table.table-count td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    border-style: solid;
    border-color: #e4e4e4;
    /* text-align: center; */
  }

  table.tftable th,
  table.tftable td {
    font-weight: 400;
    font-style: normal;
    font-size: 12px;
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #e4e4e4;
    text-align: left;
    /* text-align: center; */
  }

  .tftable {
    margin-left: 1%;
    margin-bottom: 10px;
    margin-top: 10px;
  }
  table.tftable tr:hover {
    background: #c3ecff;
  }
  .tftable > thead > tr:hover {
    background: white;
  }
</style>
